//
//  DHSearchSceneScrollView.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/14.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHSearchSceneScrollView.h"
#import "DHScenarioModel.h"
#import "DHSearchSceneItemView.h"

@implementation DHSearchSceneScrollView

- (NSMutableArray *)scenarioArr{
    if (!_scenarioArr) {
        _scenarioArr = [NSMutableArray array];
    }
    return _scenarioArr;
}

- (void)loadSceneData{
    [[DHNetAPIClient shareDHNetAPIClient] request_scenesAndBlock:^(id data, NSError *error) {
        DHScenarioListModel *scenarioList = [DHScenarioListModel modelWithDictionary:data];
        [scenarioList updateScenarioTitleArr];
        [self.scenarioArr removeAllObjects];
        [self.scenarioArr addObjectsFromArray:scenarioList.scenes];
        [self updateScenes];
    }];
}

- (void)updateScenes{
    __block CGFloat spaceX = 5;
    __block CGFloat itemLeft = spaceX;
    __weak __typeof(self)weakSelf = self;
    [self.scenarioArr enumerateObjectsUsingBlock:^(DHScenarioModel *scene, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat itemW = 30 + [scene.title widthForFont:[UIFont systemFontOfSize:14]];
        DHSearchSceneItemView *sceneItemView = [[DHSearchSceneItemView alloc] initWithFrame:CGRectMake(itemLeft, 0, itemW, weakSelf.height) andSceneTitle:scene.title];
        [weakSelf addSubview:sceneItemView];
        [sceneItemView.sceneButton addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        sceneItemView.sceneButton.tag = idx;
        itemLeft += (itemW + spaceX);
    }];
    self.contentSize = CGSizeMake(itemLeft, self.height);
}

- (void)clickAction:(UIButton *)sender{
    for (DHSearchSceneItemView *item in self.subviews) {
        if (item.sceneButton.tag != sender.tag) {
            item.sceneButton.selected = YES;
            [item clickAction:item.sceneButton];
        }
    }
    DHScenarioModel *model = self.scenarioArr[sender.tag];
    if (sender.isSelected) {
        [self.delegate searchSceneScrollViewSelected:model._id];
    }else{
        [self.delegate searchSceneScrollViewSelected:nil];
    }
}

@end
